package com.lujianfei.netease_android_viewpager2

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.lujianfei.netease_android_viewpager2.widget.setFlingDuration
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    private val mAdapter = MyAdapter()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val data = arrayListOf<String>()
        for (index in 1..10) {
            data.add("index $index")
        }
        mAdapter.setData(data)
        viewpager2?.apply {
            adapter = mAdapter
            setFlingDuration(duration = 1000)
        }
    }

    class MyAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

        private val mData = ArrayList<String>()
        private val mColors = arrayListOf(0xffff0000,0xff00ff00,0xff0000ff,0xffffff00,0xff00ffff,0xffff00ff)
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return MyViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_main,parent,false))
        }

        override fun getItemCount(): Int {
            return mData.size
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            holder.itemView.setBackgroundColor(mColors[position % mColors.size].toInt())
            if (holder is MyViewHolder) {
                holder.setText(mData[position])
            }
        }

        fun setData(data:List<String>) {
            mData.clear()
            mData.addAll(data)
            notifyDataSetChanged()
        }

        class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            fun setText(str: String) {
                val textView = itemView.findViewById<TextView>(R.id.txt_info)
                textView.text = str
            }
        }
    }
}
